package me.spring.cloud.components.starter.swagger.gateway.swagger;

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import me.spring.cloud.components.starter.swagger.gateway.properties.SwaggerProperties;
import me.spring.cloud.components.starter.swagger.gateway.dynamic.DynamicSwaggerDocumentConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description: swagger文档配置
 * @author: luffy
 * @create: 2018-09-12 17:42
 **/
@Slf4j
@Component
@Primary
@ConditionalOnProperty(name = SwaggerProperties.prefix + ".enable", havingValue = "true")
@EnableApolloConfig(DynamicSwaggerDocumentConfiguration.namespaces)
@Import(DynamicSwaggerDocumentConfiguration.class)
public class SwaggerDocumentConfiguration implements SwaggerResourcesProvider {

  @Autowired
  private SwaggerProperties swaggerProperties;

  @Override
  public List<SwaggerResource> get() {
    List resources = new ArrayList<>();
    if (swaggerProperties.isEnable()) {
      Arrays.asList(swaggerProperties.getClient()).forEach(d -> resources.add(
          swaggerResource(d.getServerName(), d.getServerLocation(), d.getVersion())
      ));
    }
    return resources;
  }

  private SwaggerResource swaggerResource(String name, String location, String version) {
    SwaggerResource swaggerResource = new SwaggerResource();
    swaggerResource.setName(name);
    swaggerResource.setLocation(location);
    swaggerResource.setSwaggerVersion(version);
    return swaggerResource;
  }
}
